package GameMgrNode

import (
	"GameLogic"
	"PBMessage"
	"Player"

	"github.com/golang/protobuf/proto"

	"git.oschina.net/yangdao/SGNet2"
	"git.oschina.net/yangdao/extlib"

	"git.oschina.net/yangdao/goerl"
)

//GameNode 一个运行中的游戏实例
type GameNode struct {
	NodeID          int64
	workNode        *goerl.Node
	MaxPlayerNumber int
	CurPlayerNumber int

	gameScene *GameLogic.GameScene
}

//NewGameNode 创建游戏节点
func NewGameNode() *GameNode {
	retNode := &GameNode{
		MaxPlayerNumber: 9,
		NodeID:          extlib.Int64UUID(),
	}
	retNode.workNode = goerl.NewNode(retNode.receiveHandler)
	retNode.workNode.UpdateFunc = retNode.update
	retNode.workNode.UpdateSpeed = 33
	return retNode
}

//Start 启动
func (gameNode *GameNode) Start() {
	gameNode.gameScene = GameLogic.NewGameScene()
	gameNode.workNode.Start()
	gameNode.gameScene.Load()
}

func (gameNode *GameNode) receiveHandler(data interface{}) {
	tuple := data.([]interface{})
	msgHead := tuple[0]
	switch msgHead {
	case ":new-player":
		//player := tuple[1].(*Player.GamePlayer)
		gameNode.gameScene.OnAddPlayer(tuple[1].(*Player.GamePlayer))
	case ":SessionStateMail":
		sess := tuple[1].(*SGNet2.Session)
		msgType := tuple[2].(int)
		if msgType == SGNet2.SGNetMsg_SessionLost {
			gameNode.gameScene.OnRemovePlayer(sess.ID)
		}
	case ":ClientMail":
		gameNode.clientMailHandler(tuple[1].(uint16), tuple[2].(proto.Message), tuple[3].(*SGNet2.Session))
	}
}

func (gameNode *GameNode) clientMailHandler(msgID uint16, msg proto.Message, sess *SGNet2.Session) {
	switch msgID {
	case PBMessage.PBID_CS_SelectUnit:
		selectUnitID := msg.(*PBMessage.CS_SelectUnit).GetUnitId()
		gameNode.gameScene.OnSelectUnit(selectUnitID, sess.ID)
	case PBMessage.PBID_CS_MoveUnit:
		dirPkg := msg.(*PBMessage.CS_MoveUnit)
		gameNode.gameScene.OnMoveUnit(sess.ID, dirPkg.GetMoveDirX(), dirPkg.GetMoveDirY(), dirPkg.GetState(), dirPkg.GetTime())
	case PBMessage.PBID_CS_RunAbility:
		pkg := msg.(*PBMessage.CS_RunAbility)
		gameNode.gameScene.OnRunAbility(sess.ID, pkg.GetAbilityName())
	}
}

func (gameNode *GameNode) update(dt int) {
	if gameNode.gameScene != nil {
		gameNode.gameScene.OnUpdate(dt)
	}
}
